<template>
  <el-dialog title="引用内容编号" :visible.sync="dialogVisible" :before-close="handleClose" fullscreen>
    <iframe id="refIframe" :src="iframeSrc" frameborder="0" style="width: 100%; height: 99%"></iframe>
    <span slot="footer">
      <el-button plain size="small" @click="handleClose">取消</el-button>
      <el-button type="primary" plain size="small" @click="confirm">插入</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getLinkUrl, findDocNodes } from '@/utils/helpers'
import tinymce from 'tinymce'
import { v4 as uuid } from 'uuid'
import { Message } from 'element-ui'

export default {
  provide() {
    return {
      pageType: ''
    }
  },
  data() {
    return {
      insertType: undefined,
      dialogVisible: false
    }
  },
  computed: {
    currentStandard() {
      return this.$store.state.xmleditor.currentStandard
    },
    iframeSrc() {
      const { origin, pathname } = window.location
      const docNo = this.currentStandard.docNo
      const search = `?editContentType=document&entry=htmlpreview&_iframe=1&docNo=${docNo}&_=${Date.now()}`
      return origin + pathname + search
    }
  },
  methods: {
    show(insertType = undefined) {
      this.insertType = insertType
      this.dialogVisible = true
      this.$nextTick(() => {
        const nodes = [...document.querySelectorAll('div.el-tree>.el-tree-node')]
        nodes.forEach((node) => {
          const contentNode = node.querySelector('.el-tree-node__content')
          const dataIndex = node.querySelector('[data-index]')?.dataset?.index
          if (contentNode && dataIndex) {
            contentNode.dataset.index = dataIndex
          }
        })
      })
    },
    handleClose() {
      this.dialogVisible = false
    },
    confirm() {
      const win = document.querySelector('#refIframe')?.contentWindow?.window
      const nodes = win?.getSelectedBlocks()
      if (!nodes.length) {
        Message.info('请先勾选需要引用的内容')
        return
      }
      if (this.insertType === 'doc') {
        const blocks = findDocNodes(win.document, nodes.map(i => i.dataset.checkedBlockId))
        this.handleClose()
        tinymce.activeEditor.fire('addDocContent', { blocks })
        Message.success('插入成功')
        return
      }
      const snList = nodes.map((node) => node.dataset.checkedContent)
      const { name, version, code, classification, id, mainContentId, docNo, category } = this.currentStandard
      const refdate = ''
      const content = code + `&nbsp;${this.currentStandard.version}版&nbsp;《${name}》&nbsp;` + snList.join('、')
      const anchor = 'a_' + nodes[0].dataset.checkedBlockId.replace(/-/g, '_')
      tinymce.activeEditor.insertContent(
        `<span
        class="noneditable ref-link ${mainContentId ? '' : 'ref-disabled'}"
        contenteditable="false"
        data-type="refchapter"
        data-refname="${name}"
        data-standardid="${id}"
        data-maincontentid="${mainContentId}"
        data-refclassification="${classification}"
        data-refdate="${refdate}"
        data-link-url="${getLinkUrl(mainContentId) || ''}"
        data-refanchor="${anchor}"
        data-docno="${docNo || ''}"
        data-refversion="${version}"
        data-refcontent="${content}"
        data-refcode="${code}"
        data-id="${uuid()}"
        data-category="${category}"
      >${content}</span>`
      )
      this.handleClose()
      tinymce.activeEditor.fire('addNewRef', { reftype: 'refchapter', code, version })
      Message.success('插入成功')
    }
  }
}
</script>

<style scoped>
::v-deep .el-dialog__headerbtn {
  top: 14px;
}
::v-deep .el-dialog__header {
  padding: 10px;
}
::v-deep .el-dialog__body {
  word-break: break-all;
  height: calc(100vh - 98px);
  overflow: auto;
  padding: 0;
  border-bottom: 1px solid #c0c0c0;
}
::v-deep .el-dialog__footer {
  padding: 10px;
}
</style>
